
package shopping

import (
	"strings"
	"errors"
	"strconv"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type ValueOrder struct {
	OrderId         int64    `orm:"column(order_id);pk" json:"-" form:"-"`     /*订单编号*/
	OrderIdStr      string   `orm:"-" json:"order_id" form:"order_id"` /*JS中整数范围是 -2^53~2^53, 即：9.007199254741*10^15，超过15位不安全*/
	AppId           string   `orm:"column(app_id);size(32)" json:"app_id" form:"app_id"`              /*  */
	MemberId        int64    `orm:"column(member_id);index" json:"member_id" form:"member_id"`     /* 买家id */
	PartnerId       int64    `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`  /*分销商ID  */
	StoreId         int64    `orm:"column(store_id);index" json:"store_id" form:"store_id"`        /* 店铺ID */
	OrderFrom       int      `orm:"column(order_from)" json:"order_from" form:"order_from"`  /*下单来源:1WEB 3android 4ios */
    OrderType       int      `orm:"column(order_type)" json:"order_type" form:"order_type"`  /* 类型：0一般订单4拼团订单*/
    FxRef           string   `orm:"column(fx_ref);size(32);null" json:"fx_ref" form:"fx_ref"` /*  分销来源 */
    MjsActivityId   int64    `orm:"column(mjs_activity_id);null" json:"mjs_activity_id" form:"-"`  /*满就送活动ID */
	MbyActivityId   int64    `orm:"column(mby_activity_id);null" json:"mby_activity_id" form:"-"`  /*满包邮活动ID */
	ActJson         string   `orm:"column(act_json);type(text);null" json:"act_json" form:"act_json"` /*各种活动的JSON数据 */
	TotalFee        float32  `orm:"column(total_fee);digits(12);decimals(2)" json:"total_fee" form:"total_fee"` /* 订单级应付金额 */
	DiscountFee     float32  `orm:"column(discount_fee);digits(12);decimals(2)" json:"discount_fee" form:"discount_fee"` /* 减免金额(包含优惠券金额) */
	DiscountSrc  string      `orm:"column(discount_src)" json:"discount_src" form:"discount_src"` //优惠来源
	MjsDiscountFee  float32  `orm:"column(mjs_discount_fee);digits(12);decimals(2)" json:"mjs_discount_fee" form:"mjs_discount_fee"` /*满减送优惠金额*/
	BalanceDiscount float32  `orm:"column(balance_discount);digits(12);decimals(2)" json:"balance_discount" form:"balance_discount"` /* 余额抵扣*/
	AdjustFee       float32  `orm:"column(adjust_fee);digits(12);decimals(2)" json:"adjust_fee" form:"adjust_fee"` /* 手工调整金额*/
	PostFee         float32  `orm:"column(post_fee);digits(12);decimals(2)" json:"post_fee" form:"post_fee"`      /* 运费*/
	PackingFee      float32  `orm:"column(packing_fee);digits(12);decimals(2)" json:"packing_fee" form:"-"` //包装费用
	
	Payment         float32  `orm:"column(payment);digits(12);decimals(2)" json:"payment" form:"payment"`        /* 实付金额*/
	TotalTax     float32     `orm:"column(total_tax);digits(12);decimals(2)" json:"total_tax" form:"-"` //总关税
	
	RefundAmount    float32  `orm:"column(refund_amount);digits(12);decimals(2)" json:"refund_amount" form:"refund_amount"` /* 退款金额*/
	IsPaid          int      `orm:"column(is_paid);default(0)" json:"is_paid" form:"is_paid"`/* 0：未支付 1： 支付*/
	ShippingCorp    string   `orm:"column(shipping_corp);null" json:"shipping_corp" form:"shipping_corp"`     /*物流公司  */
	ShippingCode    string   `orm:"column(shipping_code);null" json:"shipping_code" form:"shipping_code"`     /*物流单号  */
	DeliverName     string   `orm:"column(deliver_name);null" json:"deliver_name" form:"deliver_name"`        /*买家姓名  */
	DeliverPhone    string   `orm:"column(deliver_phone);size(256);null" json:"deliver_phone" form:"deliver_phone"`
    Email           string   `orm:"column(email);size(256);null" json:"email" form:"email"`       /*email*/
	Country         string   `orm:"column(country);null" json:"country" form:"country"`    /*国家*/
	Province        string   `orm:"column(province);null" json:"province" form:"province"` /* 省 */
	City            string   `orm:"column(city);null" json:"city" form:"city"`             /* 市 */
	District        string   `orm:"column(district);null" json:"district" form:"district"` /*地区信息，例：天津 天津市 红桥区*/
	DeliverAddress  string   `orm:"column(deliver_address);type(text);null" json:"deliver_address" form:"deliver_address"` /* */
	PostCode        string   `orm:"column(post_code);null" json:"post_code" form:"post_code"`     /*邮编*/
	Status          string   `orm:"column(status)" json:"status" form:"status"`/* 订单状态 */
	LockState       int      `orm:"column(lock_state);default(0)" json:"lock_state" form:"lock_state"`/* 锁定状态:0正常,>0是锁定,默认0 */
	RateState       int `orm:"column(evaluation_state);default(0)" json:"evaluation_state" form:"evaluation_state"`/* 评价状态 0未评价1已评价 */
    RefundState     int `orm:"column(refund_state);default(0)" json:"refund_state" form:"refund_state"`/* 退款状态:0无退款,1部分退款,2全部退款 */
	PayWayId        int      `orm:"column(pay_way_id)" json:"pay_way_id" form:"pay_way_id"`        //支付方式：1未认证支付方式2认证支付方式
	PayWayCode      int      `orm:"column(pay_way_code);default(1)" json:"pay_way_code" form:"pay_way_code"` //支付方式编码:1微信(缺省)2 余额; 9 PayalPay支付
	PaidTime        time.Time    `orm:"column(paid_time);type(datetime);null" json:"-" form:"-"`   /* 支付时间 */
    PaidTimeStr     string       `orm:"-" json:"paid_time,omitempty" form:"-"`
	DeliverTime     time.Time    `orm:"column(deliver_time);type(datetime);null" json:"-" form:"-"` /*  */
	DeliverTimeStr  string       `orm:"-" json:"deliver_time,omitempty" form:"-"`
	FinishTime      time.Time    `orm:"column(finish_time);type(datetime);null" json:"-" form:"-"`/* 订单完成时间 */
	FinishTimeStr   string       `orm:"-" json:"finish_time,omitempty" form:"-"`
	ReceiverTime    time.Time    `orm:"column(receiver_time);type(datetime);null" json:"-" form:"-"`/* 要求到货时间 */
	ReceiverTimeStr string       `orm:"-" json:"receiver_time,omitempty" form:"receiver_time"`
	CreatedAt       time.Time    `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` 
	CreatedAtStr    string       `orm:"-" json:"created_at,omitempty" form:"-"`
    UpdatedAt       time.Time    `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`         
	UpdatedAtStr    string       `orm:"-" json:"updated_at,omitempty" form:"-"`
	PickpointId     int64        `orm:"column(pickpoint_id)" json:"pickpoint_id" form:"pickpoint_id"` /* 自提点id */
	UserId          int64        `orm:"column(user_id);null" json:"user_id" form:"user_id"`       /* 经销商id */
	Note            string       `orm:"column(note);size(128);null" json:"note" form:"note"`
	Remark          string       `orm:"column(remark);size(128);null" json:"remark" form:"remark"`
	Items           []*OrderItem `orm:"reverse(many)" json:"items,omitempty" form:"-"`           
	ItemsJson       string       `orm:"-" json:"-" form:"items"`
	PostDetails     *map[string]map[string]string `orm:"-" json:"post_details,omitempty" form:"-"`   // map[item_id]map[carry_way]post_fee
	DiscountDetails map[int64]*MjsActSimple `orm:"-" json:"discount_details,omitempty" form:"-"`   // map[int64]*MjsActSimple
	MbyDetails      map[int64]*MjsActSimple `orm:"-" json:"mby_details,omitempty" form:"-"`   // map[int64]*MjsActSimple
	FlowType        int `orm:"column(flow_type);default(0)" json:"flow_type" form:"-"` /*内部流程控制字段：0一般流程1便利店消费订单流程2便利店匿名订单流程*/
	Weight          float32  `orm:"column(weight);digits(12);decimals(2)" json:"weight" form:"weight"` /*商品重量*/
	FoodId          string   `orm:"column(food_id);null" json:"food_id" form:"food_id"`  /*餐饮特定参数*/
	CouponFee      float32   `orm:"column(coupon_fee);digits(12);decimals(2)" json:"coupon_fee" form:"coupon_fee"` /*代金券或立减优惠金额*/
	AccountJson    string    `orm:"column(account_json);type(text);null" json:"account_json" form:"account_json"`
	TrueTaxesFee   float32   `orm:"column(true_taxes_fee)" json:"true_taxes_fee" form:"true_taxes_fee"` //
	ProfitStatus   int       `orm:"column(profit_status);default(0)" json:"profit_status" form:"profit_status"` /*分账状态*/
}

// 订单商品项
type OrderItem struct {
	OrderItemId int64        `orm:"column(order_item_id);pk;auto" json:"order_item_id" form:"-"`  // 
	Order        *ValueOrder `orm:"column(order_id);rel(fk);on_delete(cascade)" json:"-" `  
	OrderId      string      `orm:"-" json:"order_id" form:"-"` 
    ItemId       int64       `orm:"column(item_id)" json:"-" form:"-"`    //商品ID
    SkuId        int64       `orm:"column(sku_id)" json:"-" form:"-"`     //sku编码
    ItemIdStr    string      `orm:"-" json:"item_id" form:"-"`
    SkuIdStr     string      `orm:"-" json:"sku_id" form:"-"`
	OuterId      string      `orm:"column(outer_id);size(128);null" json:"outer_id" form:"-"`   /* 货号,和ERP对接就需要 */
	SkuOuterId   string      `orm:"column(sku_outer_id);null" json:"sku_outer_id" form:"-"` /* SKU外部ID,和ERP对接就需要 */
	Title        string      `orm:"column(title)" json:"title" form:"-"`     /* 商品名称 */
	SkuProperties string     `orm:"column(sku_properties);null" json:"sku_properties" form:"sku_properties"` /*sku 属性*/
	Image        string      `orm:"column(image)" json:"image" form:"-"`     /* 商品图片地址 */
	Quantity     int32       `orm:"column(quantity)" json:"quantity" form:"-"`  //
    SkuStocks    int32       `orm:"-" json:"sku_stocks" form:"-"`               /* sku 库存，不存储，只方便前端查看 */
	Price        float32     `orm:"column(price);digits(12);decimals(2)" json:"price" form:"-"`              //商品单价
	TotalFee     float32     `orm:"column(total_fee);digits(12);decimals(2)" json:"total_fee" form:"-"`                   //应付金额
	DiscountFee  float32     `orm:"column(discount_fee);digits(12);decimals(2)" json:"discount_fee" form:"-"` //减免金额
	DiscountSrc  string      `orm:"column(discount_src)" json:"discount_src" form:"discount_src"` //优惠来源
	PackingFee   float32     `orm:"column(packing_fee);digits(12);decimals(2)" json:"packing_fee" form:"-"` //包装费用
	Payment      float32     `orm:"column(payment);digits(12);decimals(2)" json:"payment" form:"-"`  //实付金额
	ItemTax     float32     `orm:"column(item_tax);digits(12);decimals(2)" json:"item_tax" form:"-"` //商品关税
	LimitPay     string      `orm:"column(limit_pay);null" json:"limit_pay" form:"limit_pay"`   /*支付限制:no_balance(不接受余额支付)*/
	ActivityId   int64       `orm:"column(activity_id);null" json:"activity_id" form:"-"`                    /* 活动ID */
	BargainActId int64       `orm:"column(bargain_act_id);default(0)" json:"bargain_act_id" form:"bargain_act_id"` /* 砍价活动ID */
	PintuanId         int64  `orm:"column(pintuan_id);null" json:"pintuan_id" form:"-"`                    /* 拼团活动规则ID */
	PintuanActivityId int64  `orm:"column(pintuan_activity_id);null" json:"pintuan_activity_id" form:"-"`  /* 拼团活动ID */
	StartDate    string      `orm:"column(start_date);null" json:"start_date" form:"start_date"`   
	EndDate      string      `orm:"column(end_date);null" json:"end_date" form:"end_date"`   
	ActJson      string      `orm:"column(act_json);type(text);null" json:"act_json" form:"act_json"` /*各种活动的JSON数据 */
	UpdatedAt    time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`         
	UpdatedAtStr string      `orm:"-" json:"updated_at" form:"-"`
    DeliveryAddrs string     `orm:"column(delivery_addrs);type(text);null" json:"delivery_addrs" form:"delivery_addrs"`
	Weight        float32    `orm:"column(weight);digits(12);decimals(2)" json:"weight" form:"weight"`    /* 商品重量 */
	Barcode     string       `orm:"column(barcode);size(32)" json:"barcode" form:"barcode"`   /*条码*/  
	Xtype       int32        `orm:"column(xtype)" json:"xtype" form:"xtype"`
	IsVirtual   bool         `orm:"column(is_virtual);default(false)" json:"is_virtual" form:"is_virtual"`
    TrueTaxesFee float32   `orm:"column(true_taxes_fee)" json:"true_taxes_fee" form:"true_taxes_fee"` //
}

type OrderPromotionBind struct {
	BindId          int64   `orm:"column(bind_id);pk;auto" json:"bind_id" form:"-"`                          //编号 
    OrderId         int64   `orm:"column(order_id)" json:"order_id" form:"order_id"`                         //订单号
	PromotionId     int64   `orm:"column(promotion_id)" json:"promotion_id" form:"promotion_id"`             //促销编号
	PromotionType   int32   `orm:"column(promotion_type)" json:"promotion_type" form:"-"`                    //促销类型
	Title           string  `orm:"column(title)" json:"title" form:"-"`                                      //标题
	DiscountFee     float32 `orm:"column(discount_fee);digits(12);decimals(2)" json:"discount_fee" form:"-"` //减免金额
	PresentIntegral int32   `orm:"column(present_integral)" json:"present_integral" form:"-"`                //赠送积分
    IsApply         int32   `orm:"column(is_apply)" json:"is_apply" form:"-"`                                //是否应用
    IsConfirm       int32   `orm:"column(is_confirm)" json:"is_confirm" form:"-"`                            //是否确认
}

func init() {
    orm.RegisterModel(new(ValueOrder),new(OrderItem))   
}
func AddOrder(m *ValueOrder) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddOrderItem(m *OrderItem) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiOrderItems(list []*OrderItem) (err error) {
    size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}	
	return
}

func GetOrderById(id int64) (v *ValueOrder, err error) {
	o := models.GetDefaultDB()
	v = &ValueOrder{OrderId: id}
	if err = o.Read(v); err == nil {
	    v.OrderIdStr = strconv.FormatInt(v.OrderId, 10)
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    o.LoadRelated(v, "Items")
		for _, item := range v.Items {
		    item.OrderId = v.OrderIdStr
			item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
            item.SkuIdStr = strconv.FormatInt(item.SkuId, 10)
			item.Order = nil
		}
		return v, nil
	}
	return nil, err
}

func GetOrderByMemberId(memberId int64) (v *ValueOrder, err error) {
	o := models.GetDefaultDB()
	v = &ValueOrder{MemberId: memberId}
	if err = o.Read(v, "MemberId"); err == nil {
		return v, nil
	}
	return nil, err
}

func CheckOrderExistByMember(memberId, orderId int64) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(ValueOrder)).Filter("member_id", memberId).Filter("order_id", orderId).Exist()
	return exist
}

func CheckOrderExistByPartner(partnerId, orderId int64) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(ValueOrder)).Filter("partner_id", partnerId).Filter("order_id", orderId).Exist()
	return exist
}


func GetOrderStatusById(id int64) (string, error) {
	o := models.GetDefaultDB()
	v := &ValueOrder{OrderId: id}
	if err := o.Read(v); err != nil {
		return "", err
	}
	return v.Status, nil
}

func GetAllOrders(storeIds []int64,query map[string]string,fields []string,
                  order_by map[string]string,offset int,limit int)([]*ValueOrder,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ValueOrder))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ValueOrder
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, order := range lists {
		    order.OrderIdStr = strconv.FormatInt(order.OrderId, 10)  
			order.CreatedAtStr = order.CreatedAt.Format(consts.DATETIME_FORMAT)
			order.UpdatedAtStr = order.UpdatedAt.Format(consts.DATETIME_FORMAT)
			order.PaidTimeStr = order.PaidTime.Format(consts.DATETIME_FORMAT)
			order.DeliverTimeStr = order.DeliverTime.Format(consts.DATETIME_FORMAT)
			order.FinishTimeStr = order.FinishTime.Format(consts.DATETIME_FORMAT)
			order.ReceiverTimeStr = order.ReceiverTime.Format(consts.DATETIME_FORMAT)
			o.LoadRelated(order, "Items")
			for _, item := range order.Items { 
                item.OrderId = order.OrderIdStr
                item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
                item.SkuIdStr = strconv.FormatInt(item.SkuId, 10)
			    item.Order = nil
			}
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetOpenApiOrders(partnerId, storeId int64,orderId,start,end,status string,offset,limit int)([]*ValueOrder,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ValueOrder))
	qs = qs.Filter("partner_id", partnerId)
	if storeId > 0 {
	    qs = qs.Filter("store_id", storeId)
	}
	if len(orderId) > 0 {
	    if tmp, err := strconv.ParseInt(orderId, 10, 64); err == nil {
		    qs = qs.Filter("order_id", tmp)
		}
	}
	if startTime, err := time.Parse(consts.DATETIME_FORMAT, start); err == nil {
		qs = qs.Filter("created_at__gte", startTime)
	}
	if endTime, err := time.Parse(consts.DATETIME_FORMAT, end); err == nil {
		qs = qs.Filter("created_at__lte", endTime)
	}
	if len(status) > 0 {
	    qs = qs.Filter("status", status)
	}
	cnt, err := qs.Count()
	qs = qs.OrderBy("created_at")
	var lists []*ValueOrder
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
	    for _, order := range lists {
		    order.OrderIdStr = strconv.FormatInt(order.OrderId, 10)  
			order.CreatedAtStr = order.CreatedAt.Format(consts.DATETIME_FORMAT)
			order.UpdatedAtStr = order.UpdatedAt.Format(consts.DATETIME_FORMAT)
			order.PaidTimeStr = order.PaidTime.Format(consts.DATETIME_FORMAT)
			order.DeliverTimeStr = order.DeliverTime.Format(consts.DATETIME_FORMAT)
			order.FinishTimeStr = order.FinishTime.Format(consts.DATETIME_FORMAT)
			o.LoadRelated(order, "Items")
			for _, item := range order.Items { 
                item.OrderId = order.OrderIdStr
                item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
                item.SkuIdStr = strconv.FormatInt(item.SkuId, 10)
			    item.Order = nil
			}
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetTimeoutSignOrders(delayDays int,status string,offset,limit int)([]*ValueOrder,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ValueOrder))
	curTime := time.Now().UTC()
	referTime := curTime.Add(time.Duration(delayDays)*24*time.Hour)
	qs = qs.Filter("deliver_time__lte", referTime)
	if len(status) > 0 {
	    qs = qs.Filter("status", status)
	}
	cnt, err := qs.Count()
	qs = qs.OrderBy("deliver_time")
	var lists []*ValueOrder
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetTimeoutCancelOrders(delayMinute int,status string,offset,limit int)([]*ValueOrder,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ValueOrder))
	curTime := time.Now().UTC()
	referTime := curTime.Add(time.Duration(delayMinute)*time.Minute)
	qs = qs.Filter("created_at__lte", referTime)
	if len(status) > 0 {
	    qs = qs.Filter("status", status)
	}
	cnt, err := qs.Count()
	qs = qs.OrderBy("created_at")
	var lists []*ValueOrder
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func updateOrder(m *ValueOrder, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := ValueOrder{OrderId: m.OrderId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, param...)
		return
	}
	return
}

//更新订单折扣信息和金额等
func UpdateOrderDiscountById(m *ValueOrder) (err error) {
	err = updateOrder(m, "discount_fee", "adjust_fee", "payment")
	return
}
// 更新订单付款时间、标志等
func UpdateOrderPayInfo(m *ValueOrder) (err error) {
	m.IsPaid = 1
	m.PaidTime = time.Now().UTC()
	err = updateOrder(m, "is_paid", "paid_time")
	return
}

// 更新订单支付方式
func UpdateOrderPayWayCode(m *ValueOrder) (err error) {
	err = updateOrder(m, "pay_way_code")
	return
}

func UpdateOrderPayWayCodeByOrderId(orderId int64,paywayCode int) (err error) {
	o := models.GetDefaultDB()
	m := &ValueOrder{OrderId: orderId}
	if err = o.Read(m); err != nil {
		return
	}
	m.PayWayCode = paywayCode
	err = updateOrder(m, "pay_way_code")
	return
}

// 更新订单发货时间
func UpdateOrderDeliverTime(m *ValueOrder) (err error) {
	m.DeliverTime = time.Now().UTC()
	err = updateOrder(m, "deliver_time")
	return
}

// 更新订单状态
func UpdateOrderStatus(m *ValueOrder) (err error) {
	err = updateOrder(m, "status")
	return
}

// 更新订单买家ID
func UpdateOrderMemberId(m *ValueOrder) (err error) {
	err = updateOrder(m, "member_id")
	return
}

// 更新订单内部流程编号
func UpdateOrderFlowType(m *ValueOrder) (err error) {
	err = updateOrder(m, "flow_type")
	return
}

// 更新代金券或立减优惠金额
func UpdateOrderCouponFee(m *ValueOrder) (err error) {
	err = updateOrder(m, "coupon_fee")
	return
}

// 更新分账字段
func UpdateOrderProfit(m *ValueOrder) (err error) {
	err = updateOrder(m, "profit_status")
	return
}

func UpdateOrderById(m *ValueOrder, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := ValueOrder{OrderId: m.OrderId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, param...)
		return
	}
	return
}

func updateOrderItemById(m *OrderItem, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := OrderItem{OrderItemId: m.OrderItemId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m, k...); err == nil {
			return
		}
	}
	return
}

//更新订单商品折扣信息和实付金额
func UpdateOrderItemDiscountById(m *OrderItem) (err error) {
	err = updateOrderItemById(m, "discount_fee", "payment")
	return
}

func DeleteOrder(id int64) (err error) {
	o := models.GetDefaultDB()
	v := ValueOrder{OrderId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return
		}
	}
	return
}

func GetPintuanActivityId(orderId int64) (orderItem *OrderItem, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(OrderItem))
	qs = qs.Filter("order_id", orderId)
	qs = qs.Filter("pintuan_id__gt", 0)
	qs = qs.Filter("pintuan_activity_id__gt", 0)
	orderItem = new(OrderItem)
	if err = qs.One(orderItem); err == nil {
		return orderItem, nil
	}
	return nil, err
}

func GetPintuanId(orderId int64) (orderItem *OrderItem, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(OrderItem))
	qs = qs.Filter("order_id", orderId)
	qs = qs.Filter("pintuan_id__gt", 0)
	orderItem = new(OrderItem)
	if err = qs.One(orderItem); err == nil {
		return orderItem, nil
	}
	return nil, err
}


func GetItemsTitle(orderId int64) (titles string, err error) {
	tmpTitles := ""
	orderItems := []*OrderItem{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(OrderItem))
	qs = qs.Filter("order_id", orderId)
	_, err = qs.All(&orderItems)
	for _, orderItem := range orderItems{
	   tmpAddTitle := tmpTitles + orderItem.Title
	   if len(tmpAddTitle) > 90{
	      continue
	   }
	   tmpTitles = tmpTitles + orderItem.Title + ";"
	}
	titles = tmpTitles
	return
}

//更新订单主键
func UpdateOrderId(oldOrderId, newOrderId int64) (err error) {
	o := models.GetDefaultDB()
	_, err = o.Raw("update value_order set order_id=? where order_id=?", newOrderId, oldOrderId).Exec()
	return
}

//更新订单商品外键
func UpdateOrderItemId(oldOrderId, newOrderId int64) (err error) {
	o := models.GetDefaultDB()
	_, err = o.Raw("update order_item set order_id=? where order_id=?", newOrderId, oldOrderId).Exec()
	return
}

//更新订单商品外键
func UpdateOrderItemOrderId(orderItemId, newOrderId int64) (err error) {
	o := models.GetDefaultDB()
	_, err = o.Raw("update order_item set order_id=? where order_item_id=?", newOrderId, orderItemId).Exec()
	return
}

func CheckOrderStatusValid(orderId int64,status string) bool {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ValueOrder)).Filter("order_id", orderId)
	ok := qs.Filter("status", status).Exist()
	return ok
}
